package com.im.service.fundPlan.smo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.im.MDA;
import com.im.service.dto.BaseException;
import com.im.service.dto.FixAsset;
import com.im.service.dto.FundPlan;
import com.im.service.dto.FundPlanStatic;
import com.im.service.dto.FundSource;
import com.im.service.dto.Funds;
import com.im.service.dto.InvestPlan;
import com.im.service.dto.PageQuery;
import com.im.service.dto.PlanDeclareSet;
import com.im.service.dto.ProjectStage;
import com.im.service.fixAsset.dao.IFixAssetQueryDao;
import com.im.service.fundPlan.dao.IFundPlanQueryDAO;
import com.im.service.investPlan.dao.IInvestPlanQueryDAO;
import com.im.service.investPlan.smo.IInvestPlanQuerySMO;
import com.im.service.projectInfo.dao.IFundSourceQueryDAO;
import com.im.service.projectInfo.dao.IImplementProjQueryDAO;
import com.im.service.projectInfo.smo.ProjectInfoQuerySMOImpl;
import com.im.util.JsonUtil;
import com.im.util.ListUtil;
import com.im.util.ReturnsUtil;
import com.im.util.StringUtil;
import com.im.viewmodel.fundPlan.FileVo;
import com.im.viewmodel.fundPlan.FundDetailVo;
import com.im.viewmodel.fundPlan.FundPlanListReqVo;
import com.im.viewmodel.fundPlan.FundPlanListRespVo;
import com.im.viewmodel.fundPlan.FundPlanRespVo;

import net.sf.json.JSONObject;

@Service
public class FundPlanManageQuerySMOImpl implements IFundPlanManageQuerySMO {

	private static final Logger logger = LogManager.getLogger(FundPlanManageQuerySMOImpl.class);
	
	@Autowired
	private IFundPlanQueryDAO fundPlanQueryDAO;
    @Autowired
    private ProjectInfoQuerySMOImpl projectInfoQuerySMO;
	@Autowired
	private IFundSourceQueryDAO fundSourceQueryDAO;
    @Autowired
    private IInvestPlanQueryDAO investPlanQueryDAO;
    @Autowired
    private IFundPlanQuerySMO fundPlanQuerySMO;
    @Autowired
	private IImplementProjQueryDAO implementProjQueryDAO;
	@Autowired
	private IInvestPlanQuerySMO investQuerySmo;
	@Autowired
	private IFixAssetQueryDao fixAssetQueryDao;


	@Override
	public PageQuery<FundPlanListRespVo> queryFundPlanList(String inJson,List<Integer> statusList) throws Exception {
		try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(inJson)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(inJson).append("不符合JSON格式").toString());
			}
			PageQuery<FundPlanListRespVo> page = null;
			JSONObject jsonObj = JSONObject.fromObject(inJson);
			if (jsonObj.containsKey(MDA.PAGE_QUERY_INFO)) {
				JSONObject pageInfo = jsonObj.getJSONObject(MDA.PAGE_QUERY_INFO);
				page = JsonUtil.jsonToBean(pageInfo.toString(), PageQuery.class);
				jsonObj.remove(MDA.PAGE_QUERY_INFO);
			}
			
			FundPlanListReqVo reqVo = JsonUtil.jsonToBean(jsonObj.toString(), FundPlanListReqVo.class);
			
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("reqVo", reqVo);
			param.put("statusList", statusList);
			if(page != null){
				param.put("page", page);
				PageHelper.startPage(page.getPageNumber(), page.getPageSize());
			}
			List<FundPlanListRespVo> list = fundPlanQueryDAO.queryFundPlanProjList(param);
			// 2.1获取资金信息
			fundPlanJoinFoundSource(list);
			// 获取下达文件列表
			fundPlanJoinFile(list);
			
			// 3.结果返回
			if(page != null){
				page.setTotalPages(((Page<FundPlanListRespVo>)list).getPages());
				page.setTotal(((Page<FundPlanListRespVo>)list).getTotal());
			}else{
				page = new PageQuery<FundPlanListRespVo>();
			}
			page.setRows(list);
			return page;
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			throw new Exception(ReturnsUtil.getStackTrackMessage(e));
		}
	}

	private List<FundDetailVo> getTotalBaseFunds() {
		List<FundDetailVo> total = new ArrayList<FundDetailVo>();
		FundDetailVo planProjMoney = getEachMoney(null, null, null, null, null);
		planProjMoney.setType("planProjMoney");
		total.add(planProjMoney);
		FundDetailVo implProjMoney = getEachMoney(null, null, null, null, null);
		implProjMoney.setType("implProjMoney");
		total.add(implProjMoney);
		FundDetailVo investPlanMoney = getEachMoney(null, null, null, null, null);
		investPlanMoney.setType("investPlanMoney");
		total.add(investPlanMoney);
		FundDetailVo fundPlanMoney = getEachMoney(null, null, null, null, null);
		fundPlanMoney.setType("fundPlanMoney");
		total.add(fundPlanMoney);
		FundDetailVo fundWriteMoney = getEachMoney(null, null, null, null, null);
		fundWriteMoney.setType("fundWriteMoney");
		total.add(fundWriteMoney);
		FundDetailVo fundFirstMoney = getEachMoney(null, null, null, null, null);
		fundFirstMoney.setType("fundFirstMoney");
		total.add(fundFirstMoney);
		FundDetailVo fundEndMoney = getEachMoney(null, null, null, null, null);
		fundEndMoney.setType("fundEndMoney");
		total.add(fundEndMoney);
		return total;
	}
	@Override
	public PageQuery<FundPlanRespVo> queryFundPlanListNew(String inJson, List<Integer> statusList) throws Exception {

        List<FundPlanRespVo> ls = new ArrayList<FundPlanRespVo>();


        try {
			// 1.json格式校验
			if (!JsonUtil.jsonValidate(inJson)) {
				throw new BaseException(
						new StringBuffer().append("字符串： ").append(inJson).append("不符合JSON格式").toString());
			}
			PageQuery<FundPlanRespVo> page = null;
			JSONObject jsonObj = JSONObject.fromObject(inJson);
			if (jsonObj.containsKey(MDA.PAGE_QUERY_INFO)) {
				JSONObject pageInfo = jsonObj.getJSONObject(MDA.PAGE_QUERY_INFO);
				page = JsonUtil.jsonToBean(pageInfo.toString(), PageQuery.class);
				jsonObj.remove(MDA.PAGE_QUERY_INFO);
			}

			//FundPlanListReqVo reqVo = JsonUtil.jsonToBean(jsonObj.toString(), FundPlanListReqVo.class);
			Map<String, Object> param = new HashMap<String, Object>();
			if(jsonObj.containsKey("declareSetId") && !StringUtil.isEmpty(jsonObj.getString("declareSetId"))){
				String declareSetId = jsonObj.getString("declareSetId");
				param.put("declareSetId", declareSetId);
			}
			if(jsonObj.containsKey("impleProjId") && !StringUtil.isEmpty(jsonObj.getString("impleProjId"))){
				String impleProjId = jsonObj.getString("impleProjId");
				param.put("impleProjId", impleProjId);
			}
			if(jsonObj.containsKey("developOrg") && !StringUtil.isEmpty(jsonObj.getString("developOrg"))){
				String developOrg = jsonObj.getString("developOrg");
				param.put("orgId", developOrg);
			}
			if(param==null){
				throw new BaseException("确实请求入参，请核查数据!");
			}
			param.put("statusList", statusList);
			List<FundPlanListRespVo> alllist = fundPlanQueryDAO.queryFundPlanProjListNew(param);
			if(page != null){
				param.put("page", page);
				PageHelper.startPage(page.getPageNumber(), page.getPageSize());
			}
			List<FundPlanListRespVo> list = fundPlanQueryDAO.queryFundPlanProjListNew(param);
			// 2.1获取资金信息
			FundPlanRespVo totalvo = new FundPlanRespVo();
			List<FundDetailVo> totalfunds = getTotalBaseFunds();
			List<String> fundplanIds = new ArrayList<String>();
			totalvo.setFundDetailVo(totalfunds);
            for (FundPlanListRespVo fp : list) {
				fundplanIds.add(fp.getFundPlanId());
				// 前期工作情况组装
				ProjectStage projStage = new ProjectStage();
				projStage.setStatusCd(MDA.PROJECT_STAGE_STATUS_CD_FINISH);// 已完工
				projStage.setImpleProjId(fp.getImpleProjId());
				List<ProjectStage> projStageList = implementProjQueryDAO.queryImpleProjStageList(projStage);
				StringBuffer sb = new StringBuffer();
				for (ProjectStage temp : projStageList) {
					sb.append(temp.getProjStateName()).append(":").append(temp.getApprovalInfo()).append(";");
				}
				fp.setPreWorkSituation(sb.toString());
				// 概算和三项累计查询
				List<FundDetailVo> fundDetailVos = investQuerySmo.queryFourFundSource(fp.getImpleProjId(),
						fp.getFundPlanId(), null);
				for (FundDetailVo fundDetailVo : fundDetailVos) {
					fundDetailVo.setYearDt((Integer.valueOf(fp.getYearDt()) - 1) + "");
				}
				List<String> objIds = new ArrayList<String>();
				// 5、****年填报投资计划 当年 计划填报 金额
				objIds.clear();
				objIds.add(fp.getFundPlanId());
				FundDetailVo fundWriteMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_401, objIds, null, null, "10");
                fundWriteMoney.setType("fundWriteMoney");
                fundWriteMoney.setRemark(fp.getDescription());
				fundWriteMoney.setYearDt(fp.getYearDt());
                fundDetailVos.add(fundWriteMoney);


				// 6、 ****年初审投资计划 当年 计划初审 金额
				FundDetailVo fundFirstMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_402, objIds, null, null, "10");
                fundFirstMoney.setType("fundFirstMoney");
                fundFirstMoney.setRemark(fp.getExamineDescription());
                Map<String, Object> paramfile = new HashMap<String, Object>();
                paramfile.put("uploadObjId", fp.getFundPlanId());
                paramfile.put("uploadObjType", "120");
                List<FileVo> files = fundPlanQueryDAO.queryFileListUploadsByCond(paramfile);
                if(!ListUtil.isListEmpty(files)){
                    fp.setFiles(files);
                    String fileNames ="";
                    for(FileVo f:files){
                        fileNames=fileNames + f.getAttachFullName()+"   ";
                    }
                    fundFirstMoney.setFileName(fileNames);
                }
				fundFirstMoney.setYearDt(fp.getYearDt());
                fundDetailVos.add(fundFirstMoney);


				// 7、 ****年批复投资计划 当年 计划初审 金额
				FundDetailVo fundEndMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_403, objIds, null, null, "10");
                fundEndMoney.setType("fundEndMoney");
                fundEndMoney.setRemark("");

                paramfile.clear();;
                paramfile.put("uploadObjId", fp.getFundPlanId());
                paramfile.put("uploadObjType", "160");
                List<FileVo> files1 = fundPlanQueryDAO.queryFileListUploadsByCond(paramfile);
                if(!ListUtil.isListEmpty(files1)){
                    fp.setFiles(files1);
                    String fileNames ="";
                    for(FileVo f:files1){
                        fileNames=fileNames + f.getAttachFullName()+"   ";
                    }
                    fundEndMoney.setFileName(fileNames);
                }
				fundEndMoney.setYearDt(fp.getYearDt());
                fundDetailVos.add(fundEndMoney);
                FundPlanRespVo vo = new FundPlanRespVo();
                BeanUtils.copyProperties(fp,vo);
                vo.setFundDetailVo(fundDetailVos);
                ls.add(vo);
					for (FundDetailVo t1 : totalvo.getFundDetailVo()) {
						for (FundDetailVo t2 : fundDetailVos) {
							if (t1.getType().equals(t2.getType())) {
								t1.setFundBu(new BigDecimal(t1.getFundBu()).add(new BigDecimal(t2.getFundBu()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								t1.setFundSheng(new BigDecimal(t1.getFundSheng()).add(new BigDecimal(t2.getFundSheng()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								t1.setFundGao(new BigDecimal(t1.getFundGao()).add(new BigDecimal(t2.getFundGao()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								t1.setFundShi(new BigDecimal(t1.getFundShi()).add(new BigDecimal(t2.getFundShi()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								t1.setFundQi(new BigDecimal(t1.getFundQi()).add(new BigDecimal(t2.getFundQi()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								t1.setFundOther(new BigDecimal(t1.getFundOther()).add(new BigDecimal(t2.getFundOther()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								t1.setTotal(new BigDecimal(t1.getTotal()).add(new BigDecimal(t2.getTotal()))
										.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
							}
						}
					}
            }
			// 总数大于当前页数时，统计后面的数据
			if (list != null && list.size() < alllist.size()) {
				List<FundPlanListRespVo> nextlist = new ArrayList<FundPlanListRespVo>();
				for (FundPlanListRespVo vo1 : alllist) {
					if (!fundplanIds.contains(vo1.getFundPlanId())) {
						nextlist.add(vo1);
						}
				}
				for (FundPlanListRespVo fp : nextlist) {
					// 概算和三项累计查询
					List<FundDetailVo> fundDetailVos = investQuerySmo.queryFourFundSource(fp.getImpleProjId(),
							fp.getFundPlanId(), null);
					for (FundDetailVo fundDetailVo : fundDetailVos) {
						fundDetailVo.setYearDt((Integer.valueOf(fp.getYearDt()) - 1) + "");
					}
					List<String> objIds = new ArrayList<String>();
					// 5、****年填报投资计划 当年 计划填报 金额
					objIds.clear();
					objIds.add(fp.getFundPlanId());
					FundDetailVo fundWriteMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_401, objIds, null, null,
							"10");
					fundWriteMoney.setType("fundWriteMoney");
					fundWriteMoney.setRemark(fp.getDescription());
					fundWriteMoney.setYearDt(fp.getYearDt());
					fundDetailVos.add(fundWriteMoney);

					// 6、 ****年初审投资计划 当年 计划初审 金额
					FundDetailVo fundFirstMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_402, objIds, null, null,
							"10");
					fundFirstMoney.setType("fundFirstMoney");
					fundFirstMoney.setRemark(fp.getExamineDescription());
					Map<String, Object> paramfile = new HashMap<String, Object>();
					paramfile.put("uploadObjId", fp.getFundPlanId());
					paramfile.put("uploadObjType", "120");
					List<FileVo> files = fundPlanQueryDAO.queryFileListUploadsByCond(paramfile);
					if (!ListUtil.isListEmpty(files)) {
						fp.setFiles(files);
						String fileNames = "";
						for (FileVo f : files) {
							fileNames = fileNames + f.getAttachFullName() + "   ";
						}
						fundFirstMoney.setFileName(fileNames);
					}
					fundFirstMoney.setYearDt(fp.getYearDt());
					fundDetailVos.add(fundFirstMoney);

					// 7、 ****年批复投资计划 当年 计划初审 金额
					FundDetailVo fundEndMoney = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_403, objIds, null, null,
							"10");
					fundEndMoney.setType("fundEndMoney");
					fundEndMoney.setRemark("");

					paramfile.clear();
					fundEndMoney.setYearDt(fp.getYearDt());
					fundDetailVos.add(fundEndMoney);
						for (FundDetailVo t1 : totalvo.getFundDetailVo()) {
							for (FundDetailVo t2 : fundDetailVos) {
								if (t1.getType().equals(t2.getType())) {
									t1.setFundBu(new BigDecimal(t1.getFundBu()).add(new BigDecimal(t2.getFundBu()))
											.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
									t1.setFundSheng(
											new BigDecimal(t1.getFundSheng()).add(new BigDecimal(t2.getFundSheng()))
													.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
									t1.setFundGao(new BigDecimal(t1.getFundGao()).add(new BigDecimal(t2.getFundGao()))
											.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
									t1.setFundShi(new BigDecimal(t1.getFundShi()).add(new BigDecimal(t2.getFundShi()))
											.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
									t1.setFundQi(new BigDecimal(t1.getFundQi()).add(new BigDecimal(t2.getFundQi()))
											.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
									t1.setFundOther(
											new BigDecimal(t1.getFundOther()).add(new BigDecimal(t2.getFundOther()))
													.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
									t1.setTotal(new BigDecimal(t1.getTotal()).add(new BigDecimal(t2.getTotal()))
											.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
								}
							}
						}
					}
			}
			if (statusList.size() > 1) {
				totalvo.setStatusCd(MDA.FUND_PLAN_STATUS_CD_PASS.toString());
				ls.add(totalvo);
			}
			// 3.结果返回
			if(page != null){
				page.setTotalPages(((Page<FundPlanListRespVo>)list).getPages());
				page.setTotal(((Page<FundPlanListRespVo>)list).getTotal());
			}else{
				page = new PageQuery<FundPlanRespVo>();
			}
			page.setRows(ls);
			return page;
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error(ReturnsUtil.getStackTrackMessage(e));
			}
			throw new Exception(ReturnsUtil.getStackTrackMessage(e));
		}
	}

	/**
	 * 
	 * 获取资金信息
	 * @param list 
	 */
	private void fundPlanJoinFoundSource(List<FundPlanListRespVo> list) {
		FundSource fundSource = new FundSource();
		fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND);//资金计划
		for(FundPlanListRespVo ip : list){
			fundSource.setFundSourceObj(ip.getFundPlanId());
			List<FundSource> fundSourceList = fundSourceQueryDAO.queryFoundSource(fundSource);
			for(FundSource fs : fundSourceList){
				switch (fs.getFundSourceType()) {
				case "10":
					ip.setFundSourceBu(Double.parseDouble(fs.getFundVal()));
					break;
				case "20":
					ip.setFundSourceSheng(Double.parseDouble(fs.getFundVal()));
					break;
				case "30":
					ip.setFundSourceGao(Double.parseDouble(fs.getFundVal()));
					break;
				case "40":
					ip.setFundSourceShi(Double.parseDouble(fs.getFundVal()));
					break;
				case "50":
					ip.setFundSourceQi(Double.parseDouble(fs.getFundVal()));
					break;
				default:
					break;
				}
				
			}
			//资金总额
			Double total = 0.0;
			if(ip.getFundSourceBu() != null){
				total += ip.getFundSourceBu() ;
			}
			if(ip.getFundSourceGao() != null){
				total += ip.getFundSourceGao() ;
			}
			if(ip.getFundSourceQi() != null){
				total += ip.getFundSourceQi() ;
			}
			if(ip.getFundSourceSheng() != null){
				total += ip.getFundSourceSheng() ;
			}
			if(ip.getFundSourceShi() != null){
				total += ip.getFundSourceShi() ;
			}
			ip.setTotal(BigDecimal.valueOf(total));
		}
	}

	private void fundPlanJoinFile(List<FundPlanListRespVo> list) {
		for (FundPlanListRespVo ip : list) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("uploadObjId", ip.getFundPlanId());
			param.put("uploadObjType", "160");
			List<FileVo> files = fundPlanQueryDAO.queryFileListUploadsByCond(param);
			ip.setFiles(files);
		}
	}

	@Override
	public PageQuery<FundPlanStatic> queryFundPlanStaticList(String inJson) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(inJson)) {
			throw new BaseException(
					new StringBuffer().append("字符串： ").append(inJson).append("不符合JSON格式").toString());
		}
		// 1.分页信息
		PageQuery<FundPlanStatic> page = null;
		JSONObject jsonObj = JSONObject.fromObject(inJson);
		if (jsonObj.containsKey(MDA.PAGE_QUERY_INFO)) {
			JSONObject pageInfo = jsonObj.getJSONObject(MDA.PAGE_QUERY_INFO);
			page = JsonUtil.jsonToBean(pageInfo.toString(), PageQuery.class);
			jsonObj.remove(MDA.PAGE_QUERY_INFO);
		}
		
		FundPlanStatic fundPlanStatic = JsonUtil.jsonToBean(jsonObj.toString(), FundPlanStatic.class);
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("fundPlanStatic", fundPlanStatic);
		if(page != null){
			param.put("page", page);
			PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		}
		// 2.列表查询
		List<FundPlanStatic> list = fundPlanQueryDAO.queryFundPlanStaticList(param);
		// 3.获取项目前期工作情况
		impleProjJoinProjStage(list);
		
		// 4.获取各项资金
		Calendar calendar=Calendar.getInstance();
        String thisYear=String.valueOf(calendar.get(Calendar.YEAR));
        String lastYear = String.valueOf(calendar.get(Calendar.YEAR)-1);
        List<String> objIds = new ArrayList<String>();
        List<String> fundPlanIdList = new ArrayList<String>();
        for(FundPlanStatic is : list){
        	String endYear = lastYear;
            if(is.getStartDt()!=null && !"".equals(is.getStartDt())){
                lastYear = is.getStartDt().trim().substring(0,4);
            }
			// 4.1 概算总投资 -- 实施工程投资累计
        	objIds.clear();
        	objIds.add(is.getImpleProjId());
			FundDetailVo roughTotalInvest = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_IMPLEMENT,objIds,null,null,"10");
			is.setRoughTotalInvest(roughTotalInvest);
			// 4.2 累计至上一年下达的计划 实施项目 批复与下达后
	        objIds.clear();
	        fundPlanIdList.clear();
        	InvestPlan ip = new InvestPlan();
            ip.setImpleProjId(is.getImpleProjId());
            ip.setStatusCd(MDA.FUND_PLAN_STATUS_CD_PASS + "");
            Map<String, Object> ipParam = new HashMap<String, Object>();
            ipParam.put("investPlan", ip);
            ipParam.put("page", page);
            List<InvestPlan> ips = investPlanQueryDAO.queryInvestPlanList(ipParam);
            if(!ListUtil.isListEmpty(ips)){
                for(InvestPlan o : ips){
                	fundPlanIdList.add(o.getInvestPlanId());
                }
            }
	        FundDetailVo totalIssued = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303,fundPlanIdList,null,null,"10");
	        is.setTotalIssued(totalIssued);
	        // 4.2.1 累计至上一年下达的计划--明细
	        List<Funds> totalIssuedFunds = obtainTotalFundsDetail(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303,fundPlanIdList,null,null);
	        is.setTotalIssuedFunds(totalIssuedFunds);
	        // 4.3 累计至上一年完成的投资 实施项目 在 固定资产中录入后 各项资金统计
	        objIds.clear();
			FixAsset fa = new FixAsset();
			fa.setImpleProjId(is.getImpleProjId());
			fa.setStatusCd("20");
			param.put("fixAsset", fa);
			List<FixAsset> fixAssets = fixAssetQueryDao.queryFixAssetList(param);
			for (FixAsset fixAsset : fixAssets) {
				objIds.add(fixAsset.getFixAssetId());
			}
	        FundDetailVo totalInvest = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501,objIds,null,null,"10");
	        is.setTotalInvest(totalInvest);
	        // 4.3.1 累计至上一年完成的投资--明细
	        //List<Funds> totalInvestFunds = obtainTotalFundsDetail(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501,objIds,lastYear,thisYear);
            List<Funds> totalInvestFunds = obtainTotalFundsDetailAsset(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501,objIds,null,null);
            is.setTotalInvestFunds(totalInvestFunds);
			// 4.4 累计至上一年到位资金
	        objIds.clear();
	        Map<String,Object> inMap = new HashMap<String,Object>();
			inMap.put("impleProjId",is.getImpleProjId());
			inMap.put("statusCd",MDA.FUND_PLAN_STATUS_CD_PASS);
			List<FundPlan> fundPlans = fundPlanQueryDAO.queryFundPlanList(inMap);
			if(!ListUtil.isListEmpty(fundPlans)){
				for(FundPlan f: fundPlans){
	                objIds.add(f.getFundPlanId());
	            }
			}
			FundDetailVo totalFund = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_FUND_403,objIds,null,null,"10");
	        is.setTotalFund(totalFund);
	        // 4.4.1 累计至上一年到位资金--明细
	        List<Funds> totalFundFunds = obtainTotalFundsDetail(MDA.FUND_SOURCE_OBJ_TYPE_FUND_403,objIds,null,null);
	        is.setTotalFundFunds(totalFundFunds);
			// 4.5 当年投资计划
			FundDetailVo investPlan = getEachMoney(MDA.FUND_SOURCE_OBJ_TYPE_INVEST_303,fundPlanIdList,null,null,"10");
			is.setInvestPlan(investPlan);
        }			
     	// 5.结果返回
		if(page != null){
			page.setTotalPages(((Page<FundPlanStatic>)list).getPages());
			page.setTotal(((Page<FundPlanStatic>)list).getTotal());
		}else{
			page = new PageQuery<FundPlanStatic>();
		}
		page.setRows(list);
		return page;
	}

	private List<Funds> obtainTotalFundsDetailAsset(String objType, List<String> objIds,
													String beginYear,String endYear) {
		List<Funds> list = new ArrayList<Funds>();
		if(objIds == null || objIds.size() == 0){
			return list;
		}
		Map<String,Object> inMap = new HashMap<String,Object>();
		inMap.put("objType",objType);
		inMap.put("objIds",objIds);
		inMap.put("beginYear",beginYear);
		inMap.put("endYear",endYear);
		List<Funds> fsList = fundSourceQueryDAO.queryAssetFundsContainYear(inMap);
		return  fsList;
	}
	private List<Funds> obtainTotalFundsDetail(String objType, List<String> objIds,
											   String beginYear,String endYear) {
		List<Funds> list = new ArrayList<Funds>();
		if(objIds == null || objIds.size() == 0){
			return list;
		}
		Map<String,Object> inMap = new HashMap<String,Object>();
		inMap.put("objType",objType);
		inMap.put("objIds",objIds);
		inMap.put("beginYear",beginYear);
		inMap.put("endYear",endYear);
        List<Funds> fsList = new ArrayList<Funds>();
        if(objType.startsWith("3")){
            fsList = fundSourceQueryDAO.queryInvestPlanFundsContainYear(inMap);
        } else {
            fsList = fundSourceQueryDAO.queryFundPlanFundsContainYear(inMap);
        }
		if (fsList != null && fsList.size() > 0) {
			for (Funds fund : fsList) {
				fund.setBuFund(new BigDecimal(fund.getBuFund()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				fund.setShengFund(
						new BigDecimal(fund.getShengFund()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				fund.setGaoFund(new BigDecimal(fund.getGaoFund()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				fund.setShiFund(new BigDecimal(fund.getShiFund()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				fund.setQiFund(new BigDecimal(fund.getQiFund()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				fund.setOtherFund(
						new BigDecimal(fund.getOtherFund()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				fund.setTotalFund(fund.getTotalFund().setScale(2, BigDecimal.ROUND_HALF_UP));
			}
		}
		return  fsList;
	}

	private List<Funds> obtainTotalFundsDetail_bk(String objType, List<String> objIds,
			String beginYear,String endYear) {
		List<Funds> list = new ArrayList<Funds>();
		if(objIds == null || objIds.size() == 0){
			return list;
		}
		Map<String,Object> inMap = new HashMap<String,Object>();
	    inMap.put("objType",objType);
        inMap.put("objIds",objIds);
		for (int i = Integer.valueOf(beginYear); i <= Integer.valueOf(endYear); i++) {
			inMap.put("yearDt",i);
			List<FundSource> fundSourceList = fundSourceQueryDAO.queryFundsContainYear(inMap);
			Funds fund = new Funds();
			fund.setYear(i + "");
			if (fundSourceList != null && fundSourceList.size() > 0) {
				BigDecimal total = new BigDecimal(0);
				for(FundSource fs : fundSourceList){
					switch (fs.getFundSourceType()) {
					case "10":
						fund.setBuFund(Double.parseDouble(fs.getFundVal()));
						total = total.add(new BigDecimal(fs.getFundVal()));
						break;
					case "20":
						fund.setShengFund(Double.parseDouble(fs.getFundVal()));
						total = total.add(new BigDecimal(fs.getFundVal()));
						break;
					case "30":
						fund.setGaoFund(Double.parseDouble(fs.getFundVal()));
						total = total.add(new BigDecimal(fs.getFundVal()));
						break;
					case "40":
						fund.setShiFund(Double.parseDouble(fs.getFundVal()));
						total = total.add(new BigDecimal(fs.getFundVal()));
						break;
					case "50":
						fund.setQiFund(Double.parseDouble(fs.getFundVal()));
						total = total.add(new BigDecimal(fs.getFundVal()));
						break;
					case "60":
						fund.setOtherFund(Double.parseDouble(fs.getFundVal()));
						total = total.add(new BigDecimal(fs.getFundVal()));
						break;
					default:
						break;
					}
				}
				fund.setTotalFund(total);
			} /*else {
				fund.setBuFund(0d);
				fund.setShengFund(0d);
				fund.setGaoFund(0d);
				fund.setShiFund(0d);
				fund.setQiFund(0d);
				fund.setOtherFund(0d);
				fund.setTotalFund(BigDecimal.valueOf(0));
			}*/
			if(fund.getTotalFund() != null && fund.getTotalFund().compareTo(BigDecimal.valueOf(0)) > 0){
				list.add(fund);
			}
		}
		
		return list;
	}
	
	public PageQuery<FundPlanStatic> queryFundPlanStaticList_bak(String inJson) {
		// 1.json格式校验
		if (!JsonUtil.jsonValidate(inJson)) {
			throw new BaseException(
					new StringBuffer().append("字符串： ").append(inJson).append("不符合JSON格式").toString());
		}
		String more = JsonUtil.obtainValueFromJsonObject(inJson, "more");
		
		PageQuery<FundPlanStatic> page = null;
		JSONObject jsonObj = JSONObject.fromObject(inJson);
		if (jsonObj.containsKey(MDA.PAGE_QUERY_INFO)) {
			JSONObject pageInfo = jsonObj.getJSONObject(MDA.PAGE_QUERY_INFO);
			page = JsonUtil.jsonToBean(pageInfo.toString(), PageQuery.class);
			jsonObj.remove(MDA.PAGE_QUERY_INFO);
		}
		
		FundPlanStatic fundPlanStatic = JsonUtil.jsonToBean(jsonObj.toString(), FundPlanStatic.class);
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("fundPlanStatic", fundPlanStatic);
		if(page != null){
			param.put("page", page);
			PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		}
		List<FundPlanStatic> list = fundPlanQueryDAO.queryFundPlanStaticList(param);
		if (StringUtils.isNotEmpty(more) && "1".equals(more)) {
			Calendar date = Calendar.getInstance();
			int endyear = date.get(Calendar.YEAR);
			for (FundPlanStatic staticitem : list) {
				int startyear = Integer.valueOf(staticitem.getStartDt());
				List<Funds> funds = new ArrayList<Funds>();
				for (int i = startyear; i < endyear; i++) {
					Map<String, Object> foundParam = new HashMap<String, Object>();
					foundParam.put("year", i);
					foundParam.put("impleProjId", staticitem.getImpleProjId());
					foundParam.put("fundSourceObjType",MDA.FUND_SOURCE_OBJ_TYPE_FUND);
					List<FundSource> fundSources = fundSourceQueryDAO.queryFundsByYear(foundParam);
					Funds fund = new Funds();
					fund.setYear(i + "");
					if (fundSources != null && fundSources.size() > 0) {
						Double total = 0d;
						for(FundSource fs : fundSources){
							switch (fs.getFundSourceType()) {
							case "10":
								fund.setBuFund(Double.parseDouble(fs.getFundVal()));
								total += Double.parseDouble(fs.getFundVal());
								break;
							case "20":
								fund.setShengFund(Double.parseDouble(fs.getFundVal()));
								total += Double.parseDouble(fs.getFundVal());
								break;
							case "30":
								fund.setGaoFund(Double.parseDouble(fs.getFundVal()));
								total += Double.parseDouble(fs.getFundVal());
								break;
							case "40":
								fund.setShiFund(Double.parseDouble(fs.getFundVal()));
								total += Double.parseDouble(fs.getFundVal());
								break;
							case "50":
								fund.setQiFund(Double.parseDouble(fs.getFundVal()));
								total += Double.parseDouble(fs.getFundVal());
								break;
							default:
								break;
							}
						}
						fund.setTotalFund(BigDecimal.valueOf(total));
					} else {
						fund.setBuFund(0d);
						fund.setShengFund(0d);
						fund.setGaoFund(0d);
						fund.setShiFund(0d);
						fund.setQiFund(0d);
					}
					funds.add(fund);
				}
				staticitem.setFunds(funds);
			}
		}
		
		// 获取项目前期工作情况
		impleProjJoinProjStage(list);
					
		// 3.结果返回
		if(page != null){
			page.setTotalPages(((Page<FundPlanStatic>)list).getPages());
			page.setTotal(((Page<FundPlanStatic>)list).getTotal());
		}else{
			page = new PageQuery<FundPlanStatic>();
		}
		page.setRows(list);
		return page;
	}
	
	/**
	 * 
	 * 实施项目获取项目前期工作情况（项目阶段信息表状态为30）
	 * @param list 
	 */
	private void impleProjJoinProjStage(List<FundPlanStatic> list) {
		ProjectStage projStage = new ProjectStage();
		projStage.setStatusCd(MDA.PROJECT_STAGE_STATUS_CD_FINISH);//已完工
		for(FundPlanStatic ip : list){
			projStage.setImpleProjId(ip.getImpleProjId());
			List<ProjectStage> projStageList = implementProjQueryDAO.queryImpleProjStageList(projStage);
			StringBuffer sb =  new StringBuffer();
			for(ProjectStage temp : projStageList){
				sb.append(temp.getProjStateName()).append(":").append(temp.getApprovalInfo()).append(";");
			}
			ip.setPreWorkSituation(sb.toString());
		}
	}

	@Override
	public PlanDeclareSet queryFundPlanSetDetail(Map<String, Object> paramMap) {
		return fundPlanQueryDAO.queryFundPlanSetDetail(paramMap);
	}

	@Override
	public PageQuery<PlanDeclareSet> queryFundPlanSetList(String inJson) {

		PageQuery<PlanDeclareSet> page = null;
		JSONObject jsonObj = JSONObject.fromObject(inJson);
		if (jsonObj.containsKey(MDA.PAGE_QUERY_INFO)) {
			JSONObject pageInfo = jsonObj.getJSONObject(MDA.PAGE_QUERY_INFO);
			page = JsonUtil.jsonToBean(pageInfo.toString(), PageQuery.class);
			jsonObj.remove(MDA.PAGE_QUERY_INFO);
		}
		
		PlanDeclareSet fundPlanSet = JsonUtil.jsonToBean(jsonObj.toString(), PlanDeclareSet.class);

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("fundPlanSet", fundPlanSet);
		if(page != null){
			param.put("page", page);
			PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		}
		List<PlanDeclareSet> list = fundPlanQueryDAO.queryFundPlanSetList(param);

		// 3.结果返回
		if(page != null){
			page.setTotalPages(((Page<PlanDeclareSet>)list).getPages());
			page.setTotal(((Page<PlanDeclareSet>)list).getTotal());
		}else{
			page = new PageQuery<PlanDeclareSet>();
		}
		page.setRows(list);
		return page;
	}

    /**
     * 概预算是规划工程对应的数据, 10：规划项目
     * 下达计划是项目对应的数据,  20：实施项目
     * 投资就是投资计划 30：投资计划
     * 到位资金就是资金计划 40：资金计划
     * 资金来源类型10:部补助;  20:省财政; 30:高速水运融资; 40:市州配套; 50:企业自筹
     */
    private FundDetailVo getEachMoney(String objType,List<String> objIds,String beginYear,String endYear,String statusCd){
        FundDetailVo vo = new FundDetailVo();
        if(objIds == null || objIds.size() == 0){
			return vo;
		}
        Map<String,Object> inMap = new HashMap<String,Object>();
        inMap.put("objType",objType);
        inMap.put("objIds",objIds);
        inMap.put("statusCd",statusCd);
        if(beginYear!=null){
            inMap.put("beginYear",beginYear);
        }
        inMap.put("endYear",endYear);
        List<FundSource> fundSourceList = fundSourceQueryDAO.queryFundsDetailByParam(inMap);

		BigDecimal total = new BigDecimal(0);
		BigDecimal buSum = new BigDecimal(0);
		BigDecimal shengSum = new BigDecimal(0);
		BigDecimal gaoSum = new BigDecimal(0);
		BigDecimal shiSum = new BigDecimal(0);
		BigDecimal qiSum = new BigDecimal(0);
		BigDecimal otherSum = new BigDecimal(0);

		for(FundSource fs : fundSourceList) {
			switch (fs.getFundSourceType()) {
				case "10":
				buSum = buSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
					break;
				case "20":
				shengSum = shengSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
					break;
				case "30":
				gaoSum = gaoSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
					break;
				case "40":
				shiSum = shiSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
					break;
				case "50":
				qiSum = qiSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
					break;
				case "60":
				otherSum = otherSum.add(new BigDecimal(fs.getFundVal()).setScale(2, BigDecimal.ROUND_HALF_UP));
					break;
				default:
					break;
			}
		}
		total = total.add(buSum).add(shengSum).add(gaoSum).add(shiSum).add(qiSum).add(otherSum);
		vo.setFundBu(buSum.toPlainString());
		vo.setFundSheng(shengSum.toPlainString());
		vo.setFundGao(gaoSum.toPlainString());
		vo.setFundShi(shiSum.toPlainString());
		vo.setFundQi(qiSum.toPlainString());
		vo.setFundOther(otherSum.toPlainString());
		vo.setTotal(total.toPlainString());
        return vo;
    }

    public FundPlanRespVo queryFundPlanListForGreen(String str) throws Exception{
        FundPlanRespVo vo = new FundPlanRespVo();
        try {
            // 1.json格式校验
            if (!JsonUtil.jsonValidate(str)) {
                throw new BaseException(
                        new StringBuffer().append("字符串： ").append(str).append("不符合JSON格式").toString());
            }
            JSONObject jsonObj = JSONObject.fromObject(str);
            String impleProjId= JsonUtil.getNotNullStringFromJSON(jsonObj,"impleProjId","");
			String fundPlanId = JsonUtil.getStringFromJSON(jsonObj, "fundPlanId", "");
			String yearDt = null;
			if (StringUtils.isEmpty(fundPlanId)) {
				yearDt = "yearDt";
			}
			List<FundDetailVo> fundDetailVos = investQuerySmo.queryFourFundSource(impleProjId, fundPlanId, yearDt);
            vo.setFundDetailVo(fundDetailVos);
            // 3.结果返回
            return vo;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            throw new Exception(ReturnsUtil.getStackTrackMessage(e));
        }
    }
}
